package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.User;
import cn.jhc.db.DbFactory;

/**
 * Servlet implementation class UserListServlet
 */
@WebServlet("/users.do")
public class UserListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserListServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<User> users = null;
		try {
			users = DbFactory.getUserDao().find();
			response.setContentType("text/html;charset=utf8");
			PrintWriter out = response.getWriter();
			out.println("<html><head><title>所有用户</title></head>");
			out.println("<body><table border=\"1\"><tr><th>ID</th><th>用户名</th></tr>");
			users.stream().forEach(user -> {
				out.println("<tr><td>" + user.getId() + "</td><td>" + user.getUsername() + "</td></tr>");
			});
			out.println("</table></body></html>");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendError(503);
		}
	}

}
